// ==UserScript==
// @name           Show Current Bids and Totals
// @namespace      http://www.glenncarr.com/phpbb
// @description    Show content from last post in forum listing
// @include        *viewforum.php*
// @grant		   GM_xmlhttpRequest
// @grant 		   GM_addStyle
// $LastChangedRevision: 652 $
// $LastChangedDate: 2014-01-30 03:26:03 +0000 (Thu, 30 Jan 2014) $
// ==/UserScript==
(function(){

String.prototype.stripTags = function() {
  return this.replace(/<\/?[^>]+>|&[^;]+;|^\s+|\s+$/gi,'');
}

var lastPosts = document.evaluate( "//dd[@class='lastpost']", document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );
if ( lastPosts.snapshotLength == 0 )
	return;

var WORKING_IMG_URL = "data:image/gif,GIF89a%0A%00%0A%00%91%03%00%CC%CC%CC%FFff%FF%00%00%FF%FF%FF!%FF%" +
"0BNETSCAPE2.0%03%01%00%00%00!%F9%04%05%00%00%03%00%2C%00%00%00%00%0A%00%0A%00%00%02%17%9C'r%06%80%1A%" +
"02s'%AE%3Bqk%9A%E2%C3%81%14Gz%D9Q%00%00!%F9%04%05%00%00%03%00%2C%01%00%00%00%08%00%03%00%00%02%0A%9C%" +
"136%22%83%03%00S%10%14%00!%F9%04%05%00%00%03%00%2C%00%00%00%00%06%00%06%00%00%02%0C%9C%070%11%A8%7C%A" +
"2%11%22%D2X%00%00!%F9%04%05%00%00%03%00%2C%00%00%01%00%03%00%08%00%00%02%0A%1C%608%13%C1%BE%96%10c%16" +
"%00!%F9%04%05%00%00%03%00%2C%00%00%04%00%06%00%06%00%00%02%0A%04%86c%C9%1C%E1%A0%10l%16%00!%F9%04%05%" +
"00%00%03%00%2C%01%00%07%00%08%00%03%00%00%02%0A%04%86%23b%13%A1Dz%A9%00%00!%F9%04%05%00%00%03%00%2C%0" +
"4%00%04%00%06%00%06%00%00%02%0C%9C'r%A8%BB%11%06%00%03Jz%0A%00!%F9%04%09%00%00%03%00%2C%07%00%01%00%0" +
"3%00%08%00%00%02%0A%94f%A3%1A1%BD%00%18r%14%00%3B";

GM_addStyle( 'SPAN.gncCurrentBid { font-weight: bold; background: yellow; padding: 1px 1px !important; margin-left: 5px } ' );
//GM_addStyle( 'SPAN.gncCurrentBidTotal { font-weight: normal; font-style: italic; background: white; margin-left: .5em; padding-left:0 display:inline } ' );

bids = {}
highbidders = {}
for ( var iLastPost = 1; iLastPost < lastPosts.snapshotLength; iLastPost++ )
{
	var lastPost = lastPosts.snapshotItem( iLastPost );
	var dt = lastPost.parentNode.getElementsByTagName( 'dt' )[ 0 ];
	var a = dt.getElementsByTagName( 'a' );
	if ( a.length == 0 )
		continue;
	var subjectLink = null;
	var sold = false;
	for ( var i = 0; i < a.length; i++ )
	{
		if ( /^\s*SOLD\W+/i.test( a[ i ].innerHTML ) )
			sold = true;

		if ( /^\s*(SOLD|\d{1,2}\s*\/\s*\d{1,2})/i.test( a[ i ].innerHTML ) )
		{
			subjectLink = a[ i ];
			break;
		}
	}
	if ( subjectLink == null || sold )
		continue;

	subjectLink.style.color = '#f00';
	var a = lastPost.getElementsByTagName( 'a' );
	if ( a.length != 2 )
		continue;

    var bidder = a[ 0 ].innerHTML;
    bids[ bidder ] = { total:0, bids:0 };
	a = a[ 1 ];
	var note = document.createElement( 'span' );
	note.setAttribute( "class", "gncCurrentBid" );
	note.innerHTML = ' Getting last bid... <img src="' + WORKING_IMG_URL + '" border="0" />';
	note.style.display = 'inline';
	a.parentNode.insertBefore( note, a.nextSibling );

    highbidders[ subjectLink.href ] = { note:note, bidder:bidder, bid:0 };
	GM_xmlhttpRequest( {
		method: 'GET',
		url: a.href,
		onload: getHandler( handleLastBid, note, subjectLink )
		} );
}

function getHandler( responseHandler, note, subjectLink )
{
    return function ( responseDetails )
    {
        if ( responseDetails.status == 200 )
            responseHandler( responseDetails.responseText, note, subjectLink );
        else
            note.innerHTML = 'Unable to retrieve last bid';
    }
}

function handleLastBid( responseText, note, subjectLink )
{
	var html = responseText.replace( /[\r\n]+/g, '' ).replace( /^.*(<div id="page-body">.+)<\/body>.*$/im, '$1' );
	var span = document.createElement( 'span' );
	span.innerHTML = html;
	var divs = span.getElementsByTagName( 'div' );
	for ( var iDiv = 0; iDiv < divs.length; iDiv++ )
	{
		if ( divs[ iDiv ].id == 'page-body' )
		{
			var divPageBody = divs[ iDiv ];
			var divs = divPageBody.getElementsByTagName( 'div' );
			for ( var i = 0; i < divs.length; i++ )
			{
				// check for deleted posts
				var ignore = false;
				var innerDivs = divs[ i ].getElementsByTagName( 'div' );
				for ( var id = 0; !ignore && id < innerDivs.length; id++ )
					ignore = ( innerDivs[ id ].getAttribute( "class" ) == 'ignore' );

				if ( !ignore && divs[ i ].getAttribute( "class" ) == 'postbody' )
					div = divs[ i ];
			}

			var bid = div.getElementsByTagName( 'div' )[ 0 ].innerHTML.stripTags().replace( /\D*(\d+)\D*/, '$1' );
			var bidder = note.parentNode.getElementsByTagName( 'a' )[ 0 ].innerHTML;
			note.innerHTML = '$' + bid;
			subjectLink.innerHTML += ' -- $' + bid + ' ' + bidder;
			highbidders[ subjectLink.href ].bid = parseInt( bid, 10 );
			
			bids[ bidder ].total += highbidders[ subjectLink.href ].bid;
			bids[ bidder ].bids += 1;
			for ( var hb in highbidders )
			{
			    if ( highbidders[ hb ].bid > 0 )
			    {
				    highbidders[ hb ].note.innerHTML = '$' + highbidders[ hb ].bid;
				    var noteTotal = highbidders[ hb ].note.nextSibling;
				    while ( noteTotal.nodeName == '#text' )
				        noteTotal = noteTotal.nextSibling;
				    console.log( noteTotal.nodeName );
				    if ( noteTotal.nodeName != 'SPAN' )
				    {
                    	var noteTotal = document.createElement( 'span' );
                    	noteTotal.setAttribute( "class", "gncCurrentBidTotal" );
                    	noteTotal.style.display = 'inline';
                    	highbidders[ hb ].note.parentNode.insertBefore( noteTotal, highbidders[ hb ].note.nextSibling );
				    }
                   	noteTotal.innerHTML = '(Total: $' + bids[ highbidders[ hb ].bidder ].total + ', bids: ' + bids[ highbidders[ hb ].bidder ].bids + ')';
				}
			}
			
			return;
		}
	}
}

})();